//
//  WBEmoticonKeyboardViewModel.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/9.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
let WBEmoticonCountOfOnePage = 20
class WBEmoticonKeyboardViewModel: NSObject {
    static let sharedModel = WBEmoticonKeyboardViewModel()
    
    lazy var emoticonBundle:Bundle = {
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
        let bundle = Bundle(path: path!)!
        return bundle
    }()
    
    override init()
    {
        super.init()
        //print(emoticonBundle)
    }
    /// 最近表情的数组
    lazy var recentEmotions: [WBEmoticon] = {
        return [WBEmoticon]()
    }()
    
    /// 默认表情的数组
    lazy var defaultEmotions: [WBEmoticon] = {
        return self.emoticons(path: "default/info.plist")
    }()
    
    /// emoji表情的数组
    lazy var emojiEmotions: [WBEmoticon] = {
        return self.emoticons(path: "emoji/info.plist")
    }()
    
    // 浪小花表情的数组
    lazy var lxhEmotions: [WBEmoticon] = {
        return self.emoticons(path: "lxh/info.plist")
    }()

    /// 供外界使用的表情数组--三维数组
    lazy var allEmoticons:[[[WBEmoticon]]] = {
        return [
            [self.recentEmotions],
            self.typeEmotionPages(emotions:self.defaultEmotions),
            self.typeEmotionPages(emotions:self.emojiEmotions),
            self.typeEmotionPages(emotions:self.lxhEmotions)
        ]
    }()
    private func typeEmotionPages(emotions:[WBEmoticon])->[[WBEmoticon]]{
        
        let pageCount = (emotions.count - 1)/WBEmoticonCountOfOnePage + 1
        
        var result = [[WBEmoticon]]()
        for i in 0..<pageCount{
            let loc = WBEmoticonCountOfOnePage * i
            var len = 20
            if len + loc > emotions.count{
                len = emotions.count - loc
            }
            let range = NSMakeRange(loc, len)
            let subArr = (emotions as NSArray).subarray(with: range) as! [WBEmoticon]
            result.append(subArr)
            
        }
        return result
    }
    private func emoticons(path: String) -> [WBEmoticon] {
        // 取到指定的info.plist
        let file = self.emoticonBundle.path(forResource: path, ofType: nil)!
        // 从指定路径读取数据
        let array = NSArray(contentsOfFile: file)!
        // 进行字典转模型
        let emoticons = NSArray.yy_modelArray(with: WBEmoticon.self, json: array)! as! [WBEmoticon]
        for value in emoticons{
            let p = (path as NSString).deletingLastPathComponent
            value.path = p
        }
        return emoticons
    }

}
